package com.laulkar.dataproviders;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class AlarmDbAdapter {

	public static final String KEY_ROWID = "_id";
	public static final String KEY_LINE = "line";
	public static final String KEY_START_TIME = "start_time";
	public static final String KEY_END_TIME = "end_time";

	private static final String TAG = "AlarmDbAdapter";
	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;

	/**
	 * Database creation sql statement
	 */
	private static final String DATABASE_CREATE =
		"create table subway_alarm (_id integer primary key autoincrement, " +
		"line text not null, start_time integer not null, " +
		"end_time integer not null);";

	private static final String DATABASE_NAME = "alarm";
	private static final String DATABASE_TABLE = "subway_alarm";
	private static final int DATABASE_VERSION = 2;

	private final Context mCtx;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {

			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS subway_alarm");
			onCreate(db);
		}
	}

	public AlarmDbAdapter(Context ctx) {
		this.mCtx = ctx;
	}

	public AlarmDbAdapter open() throws SQLException {
		mDbHelper = new DatabaseHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	public long createAlarm(String subway, int startTime, int endTime) {
		ContentValues initialValues = new ContentValues();

		initialValues.put(KEY_LINE, subway);
		initialValues.put(KEY_START_TIME,startTime);
		initialValues.put(KEY_END_TIME, endTime);
		return mDb.insert(DATABASE_TABLE, null, initialValues);
	}

	public boolean deleteAlarm(long rowId) {

		return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}

	public boolean updateAlarm(long rowId, String line, int start, int end) {
		ContentValues args = new ContentValues();
		args.put(KEY_LINE, line);
		args.put(KEY_START_TIME, start);
		args.put(KEY_END_TIME, end);

		return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
	}

	public Cursor fetchAllAlarms() {

		return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LINE,
				KEY_START_TIME, KEY_END_TIME}, null, null, null, null, null);
	}

	public List<Alarm> fetchAllAlarmsList() {


		Cursor c = mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LINE, 
				KEY_START_TIME, KEY_END_TIME}, 
				null, null, null, null, null);

		ArrayList<Alarm> alarms = new ArrayList<Alarm>();
		if(c == null || c.getCount() == 0)
			return alarms;

		c.moveToFirst();
		alarms.add(new Alarm(c.getString(1), c.getInt(2), c.getInt(3), c.getInt(0)));

		while(c.moveToNext())
		{
			alarms.add(new Alarm(c.getString(1), c.getInt(2), c.getInt(3), c.getInt(0)));
		}
		c.close();
		return alarms;
	}

	public List<Alarm> checkAlarms()
	{
		Date d = new Date();
		int current = d.getHours() * 100 + d.getMinutes();
		Cursor c = mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LINE, 
				KEY_START_TIME, KEY_END_TIME}, 
				null, null, null, null, null);
		if(c == null || c.getCount() == 0)
			return null;

		ArrayList<Alarm> alarms = new ArrayList<Alarm>();

		c.moveToFirst();
		int start = c.getInt(2);
		int end = c.getInt(3);
		if(checkIfBetween(current, start, end))
		{
			alarms.add(new Alarm(c.getString(1), c.getInt(2), c.getInt(3), c.getInt(0)));
		}

		while(c.moveToNext())
		{
			start = c.getInt(2);
			end = c.getInt(3);
			if(checkIfBetween(current, start, end))
			{
				alarms.add(new Alarm(c.getString(1), c.getInt(2), c.getInt(3), c.getInt(0)));
			}
		}
		c.close();
		if(alarms.isEmpty())
			return null;
		else
			return alarms;
	}

	public boolean checkIfBetween(int current, int start, int end)
	{
		// 24 hours
		if(start == end)
		{
			return true;
		}

		// Eg. Start 8.30 am, end 9 am
		if(start < end)
		{
			if(current >= start && current <= end)
				return true;
			else 
				return false;
		}
		else // Start 11pm, end 1 am
		{
			if(current >= end && current <= start)
				return true;
			else
				return false;
		}
	}
}
